﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.UI.HtmlControls;

namespace EislaufScb.WebForms.Views.Images
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            this.Master.ImagesNavigationMenu.MenuItemClick += new MenuEventHandler(ImagesNavigationMenu_MenuItemClick);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Do only if no postback is occured the look up for the gallery
            // folders.
            if (!IsPostBack)
            {
                // Defining the root folder the building the menu.
                string path = Server.MapPath(@"~/Images");
                ListFoldersRecursivly(new DirectoryInfo(path));

                this.Master.ImagesNavigationMenu.Visible = true;
                this.Master.ImagesNavigationMenu.Items.OfType<MenuItem>().OrderBy(menuItem => menuItem.Text);
            }
        }

        /// <summary>
        /// Walk down the directory three to build up the asp.net menu
        /// </summary>
        /// <param name="directoryInfo"></param>
        private void ListFoldersRecursivly(DirectoryInfo directoryInfo)
        {
            DirectoryInfo[] directories = directoryInfo.GetDirectories();
            MenuItem rootMenuItem = null;

            foreach (var directory in directoryInfo.GetDirectories().Where(dir => !dir.Name.Contains("svn")).ToList())
            {
                // In case that the root folder for our images is "Images" then
                // the starting node is images an the following nodes are the root nodes
                // for all the other ones.
                if (directory.Parent.Name.Equals("Images"))
                {
                    MenuItem menuItem = new MenuItem();
                    menuItem.Text = directory.Name;
                    this.Master.ImagesNavigationMenu.Items.Add(menuItem);
                }

                if (directory.GetDirectories().Count() > 0 && !directory.Name.Contains("svn"))
                {
                    rootMenuItem = this.Master.ImagesNavigationMenu.Items.Cast<MenuItem>().Where(item => item.Text.Contains(directory.Parent.Name)).FirstOrDefault();
                    if (rootMenuItem != null)
                    {
                        rootMenuItem.ChildItems.Add(new MenuItem() { Text = directory.Name });
                    }
                    ListFoldersRecursivly(directory);
                }
                else
                {
                    if (!directory.Name.Contains("svn"))
                    {
                        // Getting the root item (in case the current directory has no childdirectories jump up to levels to compare with the ValuePath of the menuItem
                        MenuItem rootItem = this.Master.ImagesNavigationMenu.Items.Cast<MenuItem>().Where(item => item.ValuePath.Contains(directory.Parent.Parent.Name)).FirstOrDefault();
                        if (rootItem != null)
                        {
                            // One the rootItem was found, for all childitems we must look up similar to the root item the corresponding childitem to add the child directory
                            MenuItem subRootItem = rootItem.ChildItems.Cast<MenuItem>().Where(item => item.ValuePath.Contains(directory.Parent.Name)).FirstOrDefault();

                            if (subRootItem != null)
                            {
                                subRootItem.ChildItems.Add(new MenuItem() { Text = directory.Name });
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// If menu is clicked the image will be rendered as image tag into the site
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImagesNavigationMenu_MenuItemClick(object sender, MenuEventArgs e)
        {            
            MenuItem menuItem = (MenuItem)e.Item;
            string path = string.Format(@"~/Images/{0}", menuItem.ValuePath);
            DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(path));
            FileInfo[] files = directoryInfo.GetFiles("*.jpg");

            ImagesDataList.DataSource = files;
            ImagesDataList.DataBind();
        }

        /// <summary>
        /// In every item, that is databound the path is newly created and added
        /// to the templated item (image)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImagesDataList_OnItemDataBound(object sender, DataListItemEventArgs e)
        {
            FileInfo file = (FileInfo)e.Item.DataItem;
            string[] fileSubPaths = file.FullName.Split('\\');

            Image image = e.Item.Controls.OfType<Image>().FirstOrDefault();

            string imagePath = string.Empty;
            int imagesFolderIndex = 0;

            // Finding the folder that is images. All folder that are before are
            // for not interest.
            for (int index = 0; index < fileSubPaths.Length; index++)
            {
                if (fileSubPaths[index].Contains("Images"))
                {
                    imagesFolderIndex = index;
                }
            }

            // After sorting out the not used folders, the folders, afert the key folder
            // images where added to the url.
            for (int index = imagesFolderIndex; index < fileSubPaths.Length; index++)
            {
                imagePath += fileSubPaths[index] + @"/";
            }


            if (image != null)
            {
                image.ImageUrl = string.Format(@"~/{0}", imagePath.Remove(imagePath.Length -1, 1));
                image.Height = 150;
                image.Width = 150;
                image.Attributes.Add("onclick", string.Format(@"ShowImageInOriginalSize('{0}')", image.ClientID));
            }
        }
    }
}